package com.ruoyi.web.controller.commerce;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.ruoyi.commerce.domain.bo.CommerceOrdersBo;
import com.ruoyi.commerce.domain.vo.CommerceOrdersVo;
import com.ruoyi.commerce.domain.vo.CommerceProductsVo;
import com.ruoyi.commerce.service.ICommerceOrdersService;
import com.ruoyi.commerce.service.ICommerceProductsService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.specific.service.IImprovingUserPointsService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单
 *
 * @author ruoyi
 * @date 2024-01-15
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/commerce/orders")
public class CommerceOrdersController extends BaseController {

    private final ICommerceOrdersService iCommerceOrdersService;

    private final IImprovingUserPointsService iImprovingUserPointsService;
    private final ISysUserService userService;

    private final ICommerceProductsService iCommerceProductsService;

    /**
     * 查询订单列表
     */
    @SaCheckPermission("commerce:orders:list")
    @GetMapping("/list")
    public TableDataInfo<CommerceOrdersVo> list(CommerceOrdersBo bo, PageQuery pageQuery) {
        TableDataInfo<CommerceOrdersVo> list = iCommerceOrdersService.queryPageList(bo, pageQuery);
        List<CommerceOrdersVo> voList = list.getRows();
        voList.forEach(item->{
            SysUser user = userService.selectUserById(item.getUserId());
            item.setUserName(user.getUserName());
            item.setNickName(user.getNickName());
            CommerceProductsVo productsVo = iCommerceProductsService.queryById(item.getProductId());
            item.setProductName(productsVo.getProductName());
        });
        list.setRows(voList);
        return list;
    }

    /**
     * 导出全部订单列表
     */
    @SaCheckPermission("commerce:orders:export")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/exportAll")
    public void exportAll(CommerceOrdersBo bo, HttpServletResponse response) {
        List<CommerceOrdersVo> list = iCommerceOrdersService.queryList(bo);
        ExcelUtil.exportExcel(list, "订单", CommerceOrdersVo.class, response);
    }

    /**
     * 导出选择订单列表
     */
    @SaCheckPermission("commerce:orders:export")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/exportSelect/{ids}")
    public void exportSelect(@NotEmpty(message = "主键不能为空")
                                 @PathVariable Collection<Long> ids, HttpServletResponse response) {
        List<CommerceOrdersVo> list = iCommerceOrdersService.queryByIds(ids);
        ExcelUtil.exportExcel(list, "订单", CommerceOrdersVo.class, response);
    }

    /**
     * 获取订单详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("commerce:orders:query")
    @GetMapping("/{id}")
    public R<CommerceOrdersVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iCommerceOrdersService.queryById(id));
    }

    /**
     * 获取订单详细信息
     *
     * @param userId 主键
     */
    @SaCheckPermission("commerce:orders:query")
    @GetMapping("/orderStatusCount/{userId}")
    public R<Long[]> getOrderTotalInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long userId) {
        List<CommerceOrdersVo> ordersVos = iCommerceOrdersService.queryListByUserId(userId);
        // 使用Stream API对订单状态进行分类并统计数量，并将不存在的状态设置为0
        Map<String, Long> statusCount = ordersVos.stream()
                .collect(Collectors.groupingBy(
                        CommerceOrdersVo::getStatus,
                        Collectors.counting()
                ));

        // 将不存在的状态设置为0
        Long[] counts = new Long[4];
        for (int i = 0; i < 4; i++) {
            counts[i] = statusCount.getOrDefault(String.valueOf(i), 0L);
        }
        return R.ok(counts);
    }

    /**
     * 新增订单
     */
    @SaCheckPermission("commerce:orders:add")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping
    public R<Void> add(@Validated(AddGroup.class) @RequestBody CommerceOrdersBo bo) {
        Long userId = bo.getUserId();
        BigDecimal points = bo.getTotalPrice();

        if (!iImprovingUserPointsService.checkUserPointsGreaterThanOrEqualTo(userId, points)) {
            return R.fail("用户积分不足");
        }else {
            iImprovingUserPointsService.deductPointsByUserId(userId, points);
        }

        return toAjax(iCommerceOrdersService.insertByBo(bo));
    }

    /**
     * 修改订单
     */
    @SaCheckPermission("commerce:orders:edit")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody CommerceOrdersBo bo) {
        return toAjax(iCommerceOrdersService.updateByBo(bo));
    }

    /**
     * 删除订单
     *
     * @param ids 主键串
     */
    @SaCheckPermission("commerce:orders:remove")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iCommerceOrdersService.deleteWithValidByIds(Arrays.asList(ids), true));
    }
}
